<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\User;

class CheckToken
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        // $token = substr($request->header('Authorization'), 7);
        $token = $request->header('Authorization');
        $UserId = $request->header('UserId');
        if (!$token) {
            return response()->json([
                'code' => 300,
                'msg'  => '请先登录！',
                'data' => [],
            ], 300);
        } else {
            // $is = User::query()->where(['id' => $UserId, 'api_token' => $token])->count();
            $userInfo = (new User)->getUser($UserId);
            if (empty($userInfo) || $userInfo['api_token'] != $token) {
                return response()->json([
                    'code' => 300,
                    'msg'  => '登录过期，请重新登录',
                    'data' => [],
                ], 300);
            }
        }

        return $next($request);
    }
}
